package com.zheng.oa.admin.controller.hr;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zheng.common.base.BaseController;
import com.zheng.common.util.Pagination;
import com.zheng.common.validator.DecimalValidator;
import com.zheng.common.validator.LengthValidator;
import com.zheng.hr.dao.model.*;
import com.zheng.hr.rpc.api.HrInterviewRecordsService;
import com.zheng.hr.rpc.api.HrPositionService;
import com.zheng.hr.rpc.api.HrResumeExperienceService;
import com.zheng.hr.rpc.api.HrResumeService;
import com.zheng.oa.common.constant.OaResult;
import com.zheng.oa.common.constant.OaResultConstant;
import com.zheng.oa.common.constant.enums.OaStatus;
import com.zheng.oa.common.exception.OaException;
import com.zheng.upms.dao.model.UpmsUser;
import com.zheng.upms.rpc.api.UpmsApiService;
import com.zheng.upms.rpc.api.UpmsUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: xinqi
 * Date: 2018/1/19
 * Time: 14:09
 */
@Controller
@Api(value = "简历管理", description = "简历管理")
@RequestMapping("/oa/hr/resume")
public class HrResumeController extends BaseController {
    @Autowired
    private HrResumeService resumeService;
    @Autowired
    private HrPositionService positionService;
    @Autowired
    private HrResumeExperienceService resumeExperienceService;
    @Autowired
    private HrInterviewRecordsService interviewRecordsService;
    @Autowired
    private UpmsApiService apiService;
    @Autowired
    private UpmsUserService upmsUserService;

    @ApiOperation(value = "简历首页")
    @RequiresPermissions("oa:hr:resume:read")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model) {
        List<HrPosition> positions = positionService.selectList(null);
        model.addAttribute("positionList", JSON.toJSON(positions));
        return "/manage/hr/resume/index.jsp";
    }

    @ApiOperation(value = "简历列表")
    @RequiresPermissions("oa:hr:resume:read")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object list(@RequestParam(required = false, defaultValue = "1", value = "pageNumber") int pageNumber,
                       @RequestParam(required = false, defaultValue = "10", value = "pageSize") int pageSize,
                       @RequestParam(required = false, value = "sortName") String sortName,
                       @RequestParam(required = false, value = "sortOrder") String sortOrder,
                       HrResume resume) {
        resume.setPagination(new Pagination(pageNumber, pageSize, sortOrder, sortName));
        resume.getSqlMap().put("sql", apiService.sqlDataScopeFilter(getUsername(), "hr", "uu"));
        List<Map<String, Object>> rows = resumeService.selectResumePage(resume);
        int total = resumeService.selectResumePageCount(resume);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }

    @ApiOperation(value = "新增简历")
    @RequiresPermissions("oa:hr:resume:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model) {
        return "/manage/hr/resume/create.jsp";
    }

    @ApiOperation(value = "新增简历")
    @RequiresPermissions("oa:hr:resume:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object create(@RequestBody JSONObject param) {
        HrResume resume = param.toJavaObject(HrResume.class);
        List<HrResumeExperience> resumeExperiences = param.getJSONArray("experiences").toJavaList(HrResumeExperience.class);
        ComplexResult result = FluentValidator.checkAll()
                .on(resume.getRealname(), new LengthValidator(0, 20, "姓名"))
                .on(resume.getSalary(), new DecimalValidator(0, 8, "期望薪资"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new OaResult(OaResultConstant.FAILED, result.getErrors().get(0).getErrorMsg());
        }
        try {
            resumeService.insetResume(resume, resumeExperiences);
        } catch (OaException e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }

    @ApiOperation(value = "编辑简历")
    @RequiresPermissions("oa:hr:resume:update")
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String update(Model model, Integer id) {
        HrResume resume = resumeService.selectById(id);
        EntityWrapper<HrResumeExperience> resumeExperienceEntityWrapper = new EntityWrapper<>();
        resumeExperienceEntityWrapper.where("resume_id=" + resume.getId());
        List<HrResumeExperience> experiences = resumeExperienceService.selectList(resumeExperienceEntityWrapper);
        if (experiences.size() < 1) {
            experiences.add(new HrResumeExperience());
        }
        Integer positionId = resume.getPositionId();
        if (null != positionId) {
            HrPosition hrPosition = positionService.selectById(positionId);
            model.addAttribute("position", hrPosition);
        }
        model.addAttribute("resume", resume);
        model.addAttribute("experiences", experiences);
        return "/manage/hr/resume/update.jsp";
    }

    @ApiOperation(value = "编辑简历")
    @RequiresPermissions("oa:hr:resume:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(@RequestBody JSONObject param) {
        HrResume resume = param.toJavaObject(HrResume.class);
        List<HrResumeExperience> resumeExperiences = param.getJSONArray("experiences").toJavaList(HrResumeExperience.class);
        ComplexResult result = FluentValidator.checkAll()
                .on(resume.getRealname(), new LengthValidator(0, 20, "姓名"))
                .on(resume.getSalary(), new DecimalValidator(0, 12, "期望薪资整数部分"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new OaResult(OaResultConstant.FAILED, result.getErrors().get(0).getErrorMsg());
        }
        try {
            resumeService.updateResume(resume, resumeExperiences);
        } catch (OaException e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }

    @ApiOperation(value = "删除招聘计划")
    @RequiresPermissions("oa:hr:recruitPlan:delete")
    @RequestMapping(value = "/delete/{ids}", method = RequestMethod.GET)
    @ResponseBody
    public Object delete(@PathVariable("ids") String ids) {
        if (resumeService.deleteBatchIds(ids)) {
            return new OaResult(OaResultConstant.SUCCESS, null);
        } else {
            return new OaResult(OaResultConstant.FAILED, null);
        }
    }

    @ApiOperation(value = "新增面试记录")
    @RequiresPermissions("oa:hr:resume:update")
    @RequestMapping(value = "/insertInterviewRecords", method = RequestMethod.GET)
    public String insertInterviewRecords(@RequestParam("id") Integer resumeId, Model model) {
        model.addAttribute("resumeId", resumeId);
        return "/manage/hr/resume/createInterview.jsp";
    }

    @ApiOperation(value = "新增面试记录")
    @RequiresPermissions("oa:hr:resume:update")
    @RequestMapping(value = "/insertInterviewRecords", method = RequestMethod.POST)
    @ResponseBody
    public Object insertInterviewRecords(@RequestBody HrInterviewRecords interviewRecords) {
        UpmsUser upmsUser = apiService.selectUpmsUserByUsername(getUsername());
        if (null != upmsUser) {
            interviewRecords.setCuser(upmsUser.getUserId());
        }
        if (interviewRecordsService.insert(interviewRecords)) {
            return new OaResult(OaResultConstant.SUCCESS, null);
        }
        return new OaResult(OaResultConstant.FAILED, null);
    }

    @ApiOperation(value = "查看面试记录")
    @RequiresPermissions("oa:hr:resume:read")
    @RequestMapping(value = "/interviewRecordsList", method = RequestMethod.GET)
    public String interviewRecordsList(@RequestParam("id") Integer resumeId, Model model) {
        EntityWrapper<HrInterviewRecords> interviewRecordsEntityWrapper = new EntityWrapper<>();
        interviewRecordsEntityWrapper.where("resume_id=" + resumeId);
        List<HrInterviewRecords> interviewRecordsList = interviewRecordsService.selectList(interviewRecordsEntityWrapper);
        for (HrInterviewRecords interviewRecords : interviewRecordsList) {
            if (StringUtils.isNotBlank(interviewRecords.getInterviewer())) {
                //获取全部面试官名称
                String names = "";
                String interviewers = interviewRecords.getInterviewer();
                String[] interviewerArray = interviewers.split(",");
                for (String userId : interviewerArray) {
                    Integer id = Integer.parseInt(userId);
                    UpmsUser upmsUser = upmsUserService.selectById(id);
                    if (null != upmsUser) {
                        names += upmsUser.getRealname() + " ";
                    }
                }
                interviewRecords.setInterviewer(names);
            }
        }
        model.addAttribute("interviewRecordsList", interviewRecordsList);
        return "/manage/hr/resume/interviewList.jsp";
    }

    @ApiOperation(value = "修改面试记录")
    @RequiresPermissions("oa:hr:resume:update")
    @RequestMapping(value = "/updateInterviewRecords", method = RequestMethod.GET)
    public String updateInterviewRecords(@RequestParam("id") Integer id, Model model) {
        HrInterviewRecords interviewRecords = interviewRecordsService.selectById(id);
        EntityWrapper<HrPersonalRecords> personalRecordsEntityWrapper = new EntityWrapper<>();
        //展示未锁定的用户
        personalRecordsEntityWrapper.where("is_inservice=true");
        model.addAttribute("interviewRecords", interviewRecords);
        return "/manage/hr/resume/updateInterview.jsp";
    }

    @ApiOperation(value = "修改面试记录")
    @RequiresPermissions("oa:hr:resume:update")
    @RequestMapping(value = "/updateInterviewRecords", method = RequestMethod.POST)
    @ResponseBody
    public Object updateInterviewRecords(@RequestBody HrInterviewRecords interviewRecords) {
        UpmsUser upmsUser = apiService.selectUpmsUserByUsername(getUsername());
        if (null != upmsUser) {
            interviewRecords.setCuser(upmsUser.getUserId());
        }
        if (interviewRecordsService.updateById(interviewRecords)) {
            return new OaResult(OaResultConstant.SUCCESS, null);
        }
        return new OaResult(OaResultConstant.FAILED, null);
    }

    @ApiOperation(value = "删除面试记录")
    @RequiresPermissions("oa:hr:resume:update")
    @RequestMapping(value = "/deleteInterviewRecords", method = RequestMethod.GET)
    @ResponseBody
    public Object deleteInterviewRecords(Integer id) {
        if (interviewRecordsService.deleteById(id)) {
            return new OaResult(OaResultConstant.SUCCESS, null);
        }
        return new OaResult(OaResultConstant.FAILED, null);
    }
    //todo 导出
}
